package com.example.shopping.controller;

import com.example.shopping.dto.CartItem;
import com.example.shopping.dto.OrderGroup;
import com.example.shopping.dto.OrderItem;
import com.example.shopping.entity.Address;
import com.example.shopping.entity.Category;
import com.example.shopping.entity.User;
import com.example.shopping.mapper.CategoryMapper;
import com.example.shopping.service.AddressService;
import com.example.shopping.service.CartService;
import com.example.shopping.service.CategoryService;
import com.example.shopping.service.OrderService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
public class OrderController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @Autowired
    CategoryService categoryService;

    @GetMapping("/order/add")
    public String orderadd(HttpSession session, Model model) {
        //获取登录用户收货地址以及购物车数据
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        Integer userId = user.getId();
        List<Address> addressList = addressService.getAddress(userId);
        model.addAttribute("addresses", addressList);
        List<CartItem> car = cartService.getCar(userId);
        model.addAttribute("carItems", car);
        //获取总价格
        Double totalPrice = cartService.getTotalPrice(userId);
        model.addAttribute("totalPrice", totalPrice);
        return "order_add";
    }

    @PostMapping("/order/submit")
    public String ordersubmit(Integer addressId, String payType, HttpSession session, Model model) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        Integer userId = user.getId();
        //生成订单号并返回
        String orderNo = orderService.submitOrder(userId, addressId, user.getTelphone(), payType, session);
        //获取总金额
        Double totalPrice = cartService.getTotalPrice(userId);
        model.addAttribute("OrderNo", orderNo);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("payType", payType);
        return "order_submit";
    }

    //支付
    @PostMapping("/order/pay/now")
    @ResponseBody
    public String payOrder(String orderId,HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null || "".equals(orderId)) {
            return "login";
        }
        Integer userId = user.getId();
        return orderService.payOrder(userId, orderId,session);
    }

    //进入支付是否成功页面
    @GetMapping("/alipay/return")
    public String returnOrder(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        String orderId = session.getAttribute("orderId").toString();
        if (user == null ) {
            return "login";
        }
        if(orderId == null || "".equals(orderId)) {
            return "redirect:/car";
        }
        Integer userId = user.getId();
        //模拟结算订单
        orderService.orderSuccess(orderId,userId);
        return "pay_suc";
    }

    @GetMapping("/orders")
    public String orders(HttpSession session, Model model) {
        //拿到登录用户的所有订单数据并展示
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "login";
        }
        Integer userId = user.getId();
        //拿到该用户的订单数据并整理成页面所需格式
        List<OrderItem> orderlist = orderService.getOrder(userId);
        //整理成订单数组的形式
        //将订单明细列表转换为订单组列表
        Map<String, List<OrderItem>> orderMap = orderlist.stream()
                .collect(Collectors.groupingBy(OrderItem::getNumber));
        //将订单组列表转换为订单组列表
        List<OrderGroup> orderGroups = orderMap.entrySet().stream()
                .map(entry -> new OrderGroup(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
//        System.out.println("orderGroups = " + orderGroups);
        model.addAttribute("orderGroups", orderGroups);


        List<Category> categories = categoryService.getAll();
        model.addAttribute("categories", categories);
        return "orders";
    }

}
